package com.sonic.error.base;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * WrappingException class.<br>
 *
 * @author <b>Adam Dec</b><br><i>Copyright &#169; 2008</i>
 * @category com.sonic.error.base
 * @project mQuotes-Middleware
 * @since 2008-10-05
 * @version 1.0
 */
@SuppressWarnings("serial")
public abstract class WrappingException extends Exception {
	private Throwable rootCause = null;

	public WrappingException() {
		super();
	}

	/**
	 * Constructor. 
	 * @param message Exception message   
	 */
	public WrappingException(String message) {
		super(message);
	}

	/**
	 * Constructor.  
	 * @param message Exception message 
	 * @param rootCause Root exception
	 */
	public WrappingException(String message, Throwable rootCause) {
		super(message);
		this.rootCause = rootCause;
	}

	/**
	 * Constructor.
	 * @param rootCause Root exception
	 */
	public WrappingException(Throwable rootCause) {
		super(rootCause.getLocalizedMessage());
		this.rootCause = rootCause;
	}

	/**
	 * Returns the rootCause. 
	 * @return Throwable
	 */
	public Throwable getRootCause() {
		return rootCause;
	}

	public String getMessage() {
		String msg = super.getMessage();
		if (rootCause == null)
			return msg;
		if (msg == null || msg.length() == 0)
			return "nested exception is: " + rootCause;
		else
			return msg + "; nested exception is: " + rootCause;
	}

	public void printStackTrace(PrintStream ps) {
		if (rootCause != null) {
			ps.println(this);
			rootCause.printStackTrace(ps);
		}
		super.printStackTrace(ps);
	}

	public void printStackTrace() {
		printStackTrace(System.err);
	}

	public void printStackTrace(PrintWriter pw) {
		if (rootCause != null) {
			pw.println(this);
			rootCause.printStackTrace(pw);
		}
		super.printStackTrace(pw);
	}

	public String getStringStackTrace() {
		StringWriter s = new StringWriter();
		printStackTrace(new PrintWriter(s));
		return s.toString();
	}
}